﻿using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Castle.Core;
using Castle.Core.Resource;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;

namespace WebSite
{
    public class WindsorControllerFactory : DefaultControllerFactory
    {
        WindsorContainer container;

        //Constructor does the following:
        //1. Sets up a new Inversion of Control Container
        //2. Registers all components specified in web.config
        //3. Registers all controller types as components
        public WindsorControllerFactory()
        {
            //Instantiate a controller, getting the configuration from web.config
            container = new WindsorContainer(
                new XmlInterpreter(new ConfigResource("castle")));

            // Register all controller types as transient (new one created each time a request occurs)
            var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                                  where typeof(IController).IsAssignableFrom(t)
                                  select t;
            foreach (Type t in controllerTypes)
            {
                container.AddComponentWithLifestyle(t.FullName, t, LifestyleType.Transient);
            }
        }

        //Constructs the correct controller instance for each request
        protected override IController GetControllerInstance(Type controllerType)
        {
            if (controllerType != null)
            {
                return (IController)container.Resolve(controllerType);
            }
            else
            {
                return base.GetControllerInstance(controllerType);
            }
        }
    }
}
